package org.yinweichen.llm_dataset_backend.service.impl;

import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yinweichen.llm_dataset_backend.DTO.StandardAnswerCreateDTO;
import org.yinweichen.llm_dataset_backend.DTO.StandardAnswerUpdateDTO;
import org.yinweichen.llm_dataset_backend.entity.*;
import org.yinweichen.llm_dataset_backend.repository.LlmAnswerRepository;
import org.yinweichen.llm_dataset_backend.repository.StandardAnswerRepository;
import org.yinweichen.llm_dataset_backend.repository.StandardQuestionRepository;
import org.yinweichen.llm_dataset_backend.service.StandardAnswerService;
import org.yinweichen.llm_dataset_backend.util.IdGenerator;

import java.util.Date;

@Service
@RequiredArgsConstructor
@Transactional
public class StandardAnswerServiceImpl implements StandardAnswerService {
    private final StandardAnswerRepository answerRepository;
    private final StandardQuestionRepository questionRepository;

    @Override
    public ResponseEntity<StandardAnswer> create(StandardAnswerCreateDTO request) {
        StandardQuestion question = questionRepository.findById(new StandardQuestionId(request.standardQuestionId(),request.version()))
            .orElseThrow(() -> new IllegalArgumentException("StandardQuestion not found"));

        StandardAnswer answer = StandardAnswer.builder()
            .questionId(question.getId())
            .version(request.version())
            .answer(request.answer())
            .updateTime(new Date())
            .standardQuestion(question)
            .build();
        StandardAnswer savedAnswer = answerRepository.save(answer);
        return ResponseEntity.status(HttpStatus.CREATED).body(savedAnswer);
    }
    //TODO:改变了标准回答的获取方式
    public ResponseEntity<StandardAnswer> getByQuestion(Long id,String version) {
        StandardAnswer answer = answerRepository.findById(new StandardAnswerId(id, version))
                .orElseThrow(() -> new IllegalArgumentException("暂无标准答案"));
        return ResponseEntity.ok(answer);
    }

    @Override
    @Transactional
    public ResponseEntity<StandardAnswer> update(StandardAnswerUpdateDTO request) {
        // 先检查记录是否存在
        if (!answerRepository.existsById(new StandardAnswerId(request.id(), request.version()))) {
            throw new IllegalArgumentException("StandardAnswer with id " + request.id() + " and version " + request.version() + " not found");
        }

        int updatedRows = answerRepository.updateAnswer(request.id(), request.version(), request.answer());
        if (updatedRows == 0) {
            throw new RuntimeException("Failed to update StandardAnswer, no rows affected");
        }
        return getByQuestion(request.id(), request.version());
    }
}
